﻿using EntitiesGenerator.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntitiesGenerator.Dtos
{
    public class TableColumn
    {

        public string TableName { get; set; }

        public string ColumnName { get; set; }

        public Type DataType { get; set; }

        public bool IsPrimaryKey { get; set; }

        public bool IsIdentity { get; set; }

        public bool Nullable { get; set; }

        public long Length { get; set; }

        public string Remark { get; set; }

        /// <summary>
        /// 外键
        /// </summary>
        public ForeignColumn ForeignKey { get; set; }

        /// <summary>
        /// 生成属性字符串
        /// </summary>
        /// <param name="primaryKeyOrder">主键顺序,从0开始,只有一个主键时,不需要</param>
        /// <returns></returns>
        public string GeneralPropertyString(int? primaryKeyOrder = null)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine();
            if (!this.Remark.IsNullOrWhiteSpace())
                sb.AppendLine(string.Format(EntityTemplateConst.Remark, this.Remark));

            if (this.IsPrimaryKey && primaryKeyOrder != null)
                sb.AppendLine(string.Format(EntityTemplateConst.PrimaryKeyContainOrder, primaryKeyOrder));
            else if (this.IsPrimaryKey)
                sb.AppendLine(EntityTemplateConst.PrimaryKey);

            if (this.IsIdentity)
                sb.AppendLine(EntityTemplateConst.DatabaseGeneratedIdentity);
            if (this.IsPrimaryKey && !this.IsIdentity)
                sb.AppendLine(EntityTemplateConst.DatabaseGeneratedNone);
            if (this.DataType == typeof(string) && !this.Nullable && !this.IsPrimaryKey)
                sb.AppendLine(EntityTemplateConst.Required);
            if (this.DataType == typeof(string) && this.Length <= 8000)
                sb.AppendLine(string.Format(EntityTemplateConst.StringLength, this.Length));

            sb.AppendLine($"\t\tpublic {this.DataType.ToCSharpTypeString(this.Nullable)} {this.ColumnName} {{ get; set; }}");

            if (this.ForeignKey != null)
            {
                sb.AppendLine();
                sb.AppendLine(string.Format(EntityTemplateConst.ForeignKey, this.ColumnName));
                sb.AppendLine($"\t\tpublic {this.ForeignKey.ReferencesTableName} {this.ColumnName}_{this.ForeignKey.ReferencesTableName} {{ get; set; }}");
            }

            return sb.ToString();
        }
    }


}
